package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.user.LoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
@Component
public class LoginServiceImpl implements LoginService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;

    //登录
    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        //先查询user_verify表判断是否激活
        String userName = request.getUserName();
        String password = request.getUserPwd();
        //用户名不能重复，所以用用户名查询
        Example example = new Example(UserVerify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",userName);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        UserLoginResponse response = new UserLoginResponse();
        //没查到用户名
        if (userVerifies.size() == 0){
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        for (UserVerify userVerify : userVerifies) {
            String isVerify = userVerify.getIsVerify();
            //注册未激活时
            if (isVerify.equals("N")){
                response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR .getCode());
                response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR .getMessage());
                return response;
            }
            //查看注册用户是否激活
            Member query = query(userName);
            String isVerified = query.getIsVerified();
            if ("N".equals(isVerified)){
                response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR .getCode());
                response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR .getMessage());
                return response;
            }
            //已激活，先判断密码是否正确和用户名
            String name = query.getUsername();
            String ps = query.getPassword();
            AESUtil aesUtil = new AESUtil(ps);
            String decrypt = aesUtil.decrypt();
            if (!decrypt.equals(password)){
                response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
                return response;
            }
            Long id = query.getId();
            response.setId(id);
            response.setUsername(name);
            response.setEmail(query.getEmail());
            response.setState(query.getState());
            //创建token
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid",id);
            map.put("uname",name);
            String token = JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build().creatJwtToken();
            response.setToken(token);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            return response;
        }
        return response;
    }

    //查询用户信息的方法
    private Member query(String userName) {
        Example example = new Example(UserVerify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",userName);
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() != 0) {
            for (Member member : members) {
                return member;
            }
        }
        Member noo = new Member();
        return noo;
    }
    //激活用户
    @Override
    public UserVerifyResponse userVerify(String uuid, String username) {
        //根据传过来的username修改认证表
        Example example = new Example(UserVerify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid",uuid);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        UserVerifyResponse response = new UserVerifyResponse();
        //uuid是惟一的
        for (UserVerify userv : userVerifies) {
            userv.setIsVerify("Y");
            int i = userVerifyMapper.updateByPrimaryKey(userv);
            if (i == 1){
                int update = update(username);
                if (update == 200){
                    response.setCode(SysRetCodeConstants.SUCCESS.getCode());
                    response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
                    return response;
                }
            }
        }
        return response;
    }
    //修改用户信息
    private int update(String username) {
        //根据主键查询
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        List<Member> members = memberMapper.selectByExample(example);
        for (Member member : members) {
            member.setState(1);
            member.setIsVerified("Y");
            //修改isVerified
            int i = memberMapper.updateByPrimaryKey(member);
            if (i !=1){
                return 404;
            }
        }
        return 200;
    }

}
